var wxCharts = require('../../utils/wxcharts.js');
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var loadingMore = false;
var hasMore = true;
var SDKVersion = '';
var uid = 0;
var cpage = 1;

Page({

  data: {
    util: util,
    ghsData: [],

    authData: '',

    uid: 0,
    token: '',
    picker_arr: [],//picker中range属性值
    picker_index: 0,//picker中value属性值
    id_arr: [],//存储id数组
    result: "",//form提交最终结果
    userV: "",
    phoneV: "",

    org_name: '',
    tc: 0,
    hasData: false,
    footer_curr: ["", "curr"],
    userInfo: {},
    inviteCount: 0,//总邀请人数
    recents: [],
    imgDomain: app.globalData.imgDomain,
    tabCataData: [{ id: 0, title: "今日", subList:[]},
      { id: 1, title: "本周", subList: []},
      { id: 2, title: "本月", subList: []}],
    tabcurrcata: 0,
    subcurrcata: 0,
    subCataData: [{ id: 0, title: "邀请记录"},
    { id: 1, title: "提成"}],
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    wx.showLoading({
      title: 'loading',
      mask: 'true'
    });
    var that = this;
    var tc = app.get_tc();
    that.setData({
      tc:tc
    })
    

    var showIncome=options.showIncome||''
    var roomid = options.roomid||''
    that.setData({
      showIncome: showIncome,
      roomid: roomid,
    })
    if (showIncome) {
      var titlename = tc == 1 ? '我的營收' : '我的营收';
      wx.setNavigationBarTitle({
        title: titlename,
      });

    }else{
      var titlename = tc == 1 ? '營銷報表' : '营销报表';
      wx.setNavigationBarTitle({
        title: titlename,
      });
    }

    hasMore = true;
    page = 1;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('ghs_list/ghs_list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          screen_h:res.windowHeight,
          screen_w:res.windowWidth,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    this.getLoginUserInfo('');


    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      that.setData({
        org_name: res.uname
      })
    });

    var inviteuid = options.inviteuid;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      //更新数据
      that.setData({
        userInfo: res
      })
      uid = res.uid;
    }, inviteuid);
    hasMore = true;
    cpage = 1;
    
  },

  getLoginUserInfo: function (inviteuid) {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        //更新数据
        uid=res.uid,
        that.setData({
          uid: res.uid,
          token: res.token
        })
        if (!that.data.showIncome) {
          that.loadMyroom();

        } 
        wx.hideLoading();
        // that.getAuth(res.uid, res.token);
      } else {
        app.reAuthorize(reGetUserInfo);
        wx.hideLoading();
      }
    }, inviteuid);
  },

  //获取用户认证状态
  getAuth: function (uid, token) {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: '20',
        privatekey: privatekey
      },
      method: 'GET',
      success: function (responseData) {
        var data = responseData.data;
        console.log("获取已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //更新数据
          that.setData({
            authData: data,
            userV: data.realname ? data.realname : '',
            phoneV: data.phone ? data.phone : '',
            invitephoneV: data.invitephone ? data.invitephone : ''
          });
        } else {
          that.setData({
            authData: ''
          });
        }
        //读取供货商信息
        that.loadGHS(1);
      }
    });
  },


  //下拉选项改变值
  bindPickerChange: function (e) {//选项改变触发事件

    this.setData({
      picker_index: e.detail.value
    })
  },


  ////表单提交触发事件
  formSubmit: function (e) {
    app.saveFormId(e.detail.formId);
    if (this.data.authData && this.data.authData.ispay == '0'){
      wx.redirectTo({
        url: '/pages/join_pay/join_pay?coin=50&authtype=20',
      })
      return;
    }

    var that = this;
    var res = e.detail.value;
    var username = res.username;
    var mobile = res.mobile;
    var invitemobile = res.invitemobile;
    var selector = this.data.id_arr[res.selector];

    if (username == "") {
      var contentname = this.data.tc == 1 ? '姓名不能為空' : '姓名不能为空';
      wx.showModal({
        title: '提示',
        content: contentname,
        showCancel: false,
      })
      return;
    } else if (mobile == "") {
      var contentmobile = this.data.tc == 1 ? '手機號不能為空' : '手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentmobile,
        showCancel: false,
      })
      return;
    } else if (util.orgid == 18681&&invitemobile == "") {
      var contentinvitemobile = this.data.tc == 1 ? '介紹人手機號不能為空' : '介绍人手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentinvitemobile,
        showCancel: false,
      })
      return;
    } else if (selector == "0" || selector == "") {
      var contentselector = this.data.tc == 1 ? '請選擇供貨商' : '请选择供货商';
      wx.showModal({
        title: '提示',
        content: contentselector,
        showCancel: false,
      })
      return;
    }

    //提交代理商认证请求
    var ac = 'userauth'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'userauth' + that.data.token);
    if (util.orgid == 18681){
      privatekey = utilMd5.hexMD5(that.data.uid + 'userauth2' + that.data.token);
      ac = 'userauth2';
      selector=18681;
    }
    var params = {
      ac: ac,
      uid: that.data.uid,
      realname: username,
      phone: mobile,
      invitephone: invitemobile,
      catatype: "20",
      orgid: selector,
      privatekey: privatekey
    };
    console.log('代理商认证：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交代理商申请信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: "介绍人不存在",
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '申請資料已提交' : '申请资料已提交';
          that.getAuth(that.data.uid, that.data.token);
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function(res){
              // if (res.confirm) {
              //   wx.redirectTo({
              //     url: '/pages/join_pay/join_pay?coin=50&authtype=20',
              //   })
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },


  userNameInput: function (e) {
    this.setData({
      userV: e.detail.value
    })
  },

  userPhoneInput: function (e) {
    this.setData({
      phoneV: e.detail.value
    })
  },
  invitePhoneInput: function (e) {
    this.setData({
      invitephoneV: e.detail.value
    })
  },


  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          if (cpage <= 1) {
            that.setData({
              ghsData: result
            });

          } else {

            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });

          }
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }
        }

        var ghsData = that.data.ghsData;
        var picker_arr = ["请选择"];
        var id_arr = ["0"];
        var sel_index = 0;
        var orgid = '0';
        if (that.data.authData && that.data.authData.orgid){
          orgid = that.data.authData.orgid;
        }
        for (var i = 0; i < ghsData.length; i++) {
          var uid = ghsData[i].uid;
          var username = ghsData[i].username;
          if(uid == orgid){
            sel_index = i + 1;
          }
          picker_arr.push(username);
          id_arr.push(uid);
        }
        that.setData({
          picker_arr: picker_arr,
          id_arr: id_arr,
          picker_index: sel_index,
        });

        wx.hideLoading();

      }
    });
  },


  onReady: function () {
    // 页面渲染完成    
    var that = this;
    
    that.loadTakePercentageList();
  },


  

  //加载更多
  loadMore: function () {
    if (hasMore) {
      cpage++;
      // this.loadInviteList(cpage);
    }
  },


  changeTabCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) { return false; }
    else {
      this.setData({
        tabcurrcata: cur
      })
      var that = this;
      that.data.tabCataData[that.data.tabcurrcata].subList = []
      

      that.loadTakePercentageList();
    }
  },

  changeSubCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.subcurrcata == cur) { return false; }
    else {
      this.setData({
        subcurrcata: cur
      })
    }
  },

  switchTabNav: function (e) {
    console.log("e", e)
    if (e.detail.source == "touch") {
      console.log("e.detail.source")
      this.setData({
        tabcurrcata: e.detail.current,
      });
      var that = this;
      that.data.tabCataData[that.data.tabcurrcata].subList =[]
      
      that.loadTakePercentageList();


    }
  },

  //提成列表数据
  loadTakePercentageList: function () {
    var that = this;
    var tabCataData = that.data.tabCataData;
    var tabcurrcata = that.data.tabcurrcata
    util.api({
      data: {
        "publickey": util.publiccode,
        // "ac": "getgoumaiticheng",
        "ac": "getYingXiao",
        "uid": uid,
        "orgid": util.orgid,
        "num":  tabCataData[tabcurrcata].id+1
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res == false) {
          that.setData({
            hasDataTake: false
          });
        } else {
          var data = responseData.data;
          if (data && data.length > 0) {
            tabCataData[tabcurrcata].takePercentageList=data;
            that.setData({
              hasDataTake: true,
              tabCataData: tabCataData
            });
            var addDate=new Date(parseInt(data[0].addtime)*1000);
            console.log("addDate", addDate);
            that.getAxislength(addDate);
            console.log("that.data.tabCataData", that.data.tabCataData)
          }


        }

        that.setReportForm()
      }
    });
    var timestamp = (new Date()).valueOf();
    console.log("timestamp", timestamp)
  },
  loadMyroom: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getMyroom",
        "uid": uid,
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res != false) {
          
          if (responseData.data.length==1){
            // wx.navigateTo({
            //   url: '/pages/hotel-income/hotel-income?showIncome=1&roomid=' + responseData.data[0].id,
            // })
            that.setData({
              roomid:responseData.data[0].id,
              showIncome: true,
              roomList: []
            });

            that.loadTakePercentageList();
          } else {
            that.setData({
              roomList: responseData.data
            });

          }
          console.log("roomlist", that.data.roomList);

        }
      }
    });
  },
  showRoomIncome:function(e){
    console.log("getRoomIncome",e);
    var roomid=e.currentTarget.dataset.roomid
    var that=this;
    that.setData({
      roomid: roomid
    })
    wx.navigateTo({
      url: '/pages/hotel-income/hotel-income?showIncome=1&roomid=' + roomid,
    })
  },
  //赋值折线图
  setReportForm: function () {
    var that = this; 
    var tabCataData = that.data.tabCataData;
    var tabcurrcata = that.data.tabcurrcata
    var sdata=tabCataData[tabcurrcata].takePercentageList;
    console.log("sdata:", sdata);
    var categoriesd = [];
    var seriesdatad = [];
    var categoriesw = [];
    var seriesdataw = [];
    var categoriesm = [];
    var seriesdatam = [];
    if (tabcurrcata == 2) {
      for (var i = 0; i < that.data.axisLength; i++) {
        let coin = 0;
        if (sdata) {
          for (var j = 0; j < sdata.length; j++) {
            var datenum = new Date(parseInt(sdata[j].addtime) * 1000).getDate();
            if ((i + 1) == datenum) {

              coin += parseInt(sdata[j].allcoin / 100);

            }
          }

        }
        seriesdatam.push(coin)
        categoriesm.push((i + 1) + '')
      }

    }
    if (tabcurrcata == 1) {
      var week = ['日', '一', '二', '三', '四', '五', '六',]
      for (var i = 0; i < 7; i++) {
        let coin = 0;
        if (sdata) {
          for (var j = 0; j < sdata.length; j++) {
            var daynum = new Date(parseInt(sdata[j].addtime) * 1000).getDay();
            if (i == daynum) {

              coin += parseInt(sdata[j].allcoin / 100);

            }
          }
        }
        seriesdataw.push(coin)
        categoriesw.push(week[i] + '')
      }

    }
    if (tabcurrcata == 0) {
      for (var i = 0; i < 24; i++) {
        let coin = 0;
        if (sdata) {
          for (var j = 0; j < sdata.length; j++) {
            var hournum = new Date(parseInt(sdata[j].addtime) * 1000).getHours();
            if (i == hournum) {

              coin += parseInt(sdata[j].allcoin / 100);

            }
          }
        }
        seriesdatad.push(coin)
        categoriesd.push((i + 1) + '')
      }

    }

    console.log("seriesdatad:", seriesdatad);
    console.log("categoriesd:", categoriesd);
    console.log("seriesdataw:", seriesdataw);
    console.log("categoriesw:", categoriesw);
    console.log("seriesdatam:", seriesdatam);
    console.log("categoriesm:", categoriesm);
    var wxChartsD=new wxCharts({ //当日折线图配置
      canvasId: 'dReport',
      type: 'column',
      categories: categoriesd, //categories X轴
      animation: true,
      // background: '#f5f5f5',
      series: [{
        name: '日营收',
        //data: yuesimulationData.data,
        data: seriesdatad,
        color: that.data.colorSet.btnbg,
        format: function (val) {
          if (val > 0) {

            return val.toFixed(0) + '元';
          } else {
            return '';
          }
        }
      }] , 
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '日营收',
        format: function (val) {
          return val.toFixed(2);
        },
        max: 20,
        min: 0
      },
      width: 400,
      height: 200,
      dataLabel: true,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
    var wxChartsW =new wxCharts({ //周折线图配置
      canvasId: 'wReport',
      type: 'column',
      categories: categoriesw, //categories X轴
      animation: true,
      // background: '#f5f5f5',
      series: [{
        name: '周营收',
        //data: yuesimulationData.data,
        data: seriesdataw,
        color: that.data.colorSet.btnbg,
        format: function (val) {
          if (val > 0) {

            return val.toFixed(0) + '元';
          } else {
            return '';
          }
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '周营收',
        format: function (val) {
          return val.toFixed(2);
        },
        max: 20,
        min: 0
      },
      width: 400,
      height: 200,
      dataLabel: true,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
    var wxChartsM =new wxCharts({ //当月折线图配置
      canvasId: 'mReport',
      type: 'column',
      categories: categoriesm, //categories X轴
      animation: true,
      // background: '#f5f5f5',
      series: [{
        name: '月营收',
        //data: yuesimulationData.data,
        data: seriesdatam,
        color:that.data.colorSet.btnbg,
        format: function (val) {
          if(val>0){

            return val.toFixed(0) + '元';
          }else{
            return '';
          }
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '月营收',
        format: function (val) {
          return val.toFixed(0);
        },
        max: 20,
        min: 0
      },
      width: 400,
      height: 200,
      dataLabel: true,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });

  },
  getAxislength: function (addDate) {
    var that = this;
    var tabcurrcata = that.data.tabcurrcata;
    var m = addDate.getMonth() + 1
    var Y = addDate.getFullYear()
    console.log("addDate", new Date(Y, m, 0).getDate());
    if (tabcurrcata = 2) {
      that.setData({
        axisLength: new Date(Y, m, 0).getDate()
      })

    } else if (tabcurrcata = 1) {
      that.setData({
        axisLength: 7
      })

    }else{
      that.setData({
        axisLength: 24
      })
    }
  },

})